<?php
/**
 * Class to handle database connections and communication
 *
 * This DbMysql class supplies the needed database methods for
 * communication with the mysql database.
 *
 * @copyright  2009 A Memory Tree
 * @license    A Memory Tree License
 * @version    $Id:$
 * @link       http://my-trac.assembla.com/amemorytree/ticket/38
 * @since      File available since Release 0.1
 */
/*. require_module 'mysql'; .*/
require_once 'DbMySql.php';
/**
 * Handle database connections and communication
 *
 * The purpose of this db class is to supply generic
 * database communication techniques.
 *
 * @copyright  2009 A Memory Tree
 * @license    A Memory Tree License
 * @version    Release: @package_version@
 * @link       http://my-trac.assembla.com/amemorytree/ticket/38
 * @since      Class available since Release 0.1
 */
class Db
{
    /**
     * Contains MySql specific methods for communicating with the database
     * @var DbMySql
     */
    private $_dbMySql;
    /**
     * The link to the database
     *
     * @var resource
     */
    private $_link;
    /**
     * keep track of accesses
     *
     * @var array
     */
    private $_access = array();
    /**
     * Assign the database connection methods to a private property when
     * the class is created
     *
     * @return void
     */
    function __construct()
    {
        $this->_dbMySql = new DbMySql();
        $this->_access = array();
    }
    /**
     * Connect to the database server
     *
     * @param string $server Path to the server
     * @param string $name   The username
     * @param string $pass   The password
     * @return resource      TRUE on success, or FALSE on failure
     */
    function connect($server, $name, $pass)
    {
        $this->_access['connect']++;
        $db = $this->_dbMySql;
        $link = $db->connect($server, $name, $pass);
        if ($link === FALSE) {
            die ('Unable to connect to the database server');
        }
        return $link;
    }
    /**
     * Select a database from the server
     *
     * @param string $database The name of the database to be selected
     * @return boolean
     */
    public function select($database)
    {
        $this->_access['select']++;
        $conn = $this->_dbMySql->select($database);
        if ($conn === FALSE) {
            die ('Unable to select a database');
        }
        return $conn;
    }
    /**
     * Escape a value for entering into the database
     *
     * @param mixed $value
     * @return string
     */
    function escape($value)
    {
        $this->_access['escape']++;
        $stripped = (string)$value;
        if (!class_exists('Helper')) {
            if (get_magic_quotes_gpc() === 1) {
                $stripped = stripslashes((string)$value);
            }
        }
        return $this->_dbMySql->escape($stripped);
    }
    /**
     * Prepare a value for entering into the database
     *
     * @param mixed $value
     * @return string
     * @deprecated Use the escape method instead
     */
    function put($value)
    {
        return $this->escape($value);
    }
    /**
     * Unescape a value that has been retrieved from the database
     *
     * For more information about magic_quotes_runtime
     * see: http://nz2.php.net/manual/en/info.configuration.php#ini.magic-quotes-runtime
     *
     * @param mixed $value
     * @return string
     */
    function unescape($value)
    {
        $this->_access['unescape']++;
        $text = (string)$value;
        if (get_magic_quotes_runtime() === 1) {
            $text = stripslashes($text);
        }
        return $text;
    }
    /**
     * Prepare a value that has been retrieved from the database
     *
     * @param mixed $value
     * @return string
     * @deprecated Use the unescape method instead
     */
    function get($value)
    {
        return $this->unescape($value);
    }
    /**
     * Send a unique query to the database
     *
     * @param string $sql The SQL query to be sent to the database
     * @return resource   Either a resultset or true/false depending on the type of query
     */
    public function query($sql)
    {
        $this->_access['query']++;
        return $this->_dbMySql->query($sql);
    }
    /**
     * Return the id number of the newly added entry
     *
     * @return int
     */
    public function insertID() {
        $this->_access['insertid']++;
        return $this->_dbMySql->insertID();
    }
    /**
     * Get the number of rows in the result
     *
     * @param resource $result The result resource that's being evaluated
     * @return int             The number of rows in the result set, or FALSE on failure
     */
    public function rowCount($result)
    {
        $this->_access['rowcount']++;
        $count = 0;
        if (!empty($result)) {
            $count = $this->_dbMySql->rowCount($result);
        }
        return $count;
    }
    /**
     * Fetch a result row as an associative array
     *
     * @param resource $result The result resource that's being evaluated
     * @return array           An associative array of strings, or FALSE on failure
     */
    public function fetch($result)
    {
        $this->_access['fetch']++;
        return $this->_dbMySql->fetch($result);
    }
    /**
     * Fetch a result row as a numerical array
     *
     * @param resource $result The result resource that's being evaluated
     * @return array           A numerical array of strings, or FALSE if no more rows
     */
    public function fetchRow($result)
    {
        $this->_access['fetchrow']++;
        return $this->_dbMySql->fetchRow($result);
    }
    /**
     * Process the results of a query in a callback function
     *
     * @param resource $result The result resource that's being evaluated
     * @param string $func     The name of the function or class method to use
     * @param array $options   Associative array of options to be passed along
     * @return string          The concatenated results from the method function
     */
    public function process($result, $func, $options = array())
    {
        $this->_access['process']++;
        $callback = explode('::', $func);
        $processed = '';
        $n = $this->rowCount($result);
        for ($i = 0; $i < $n; $i++) {
            $row = $this->fetch($result);
            if (count($options) > 0) {
                $processed .= (string)call_user_func($callback, $row, $options);
            } else {
                $processed .= (string)call_user_func($callback, $row);
            }
        }
        return $processed;
    }
    /**
     * Free all memory associated with the result
     *
     * @param resource $result The result resource that's being evaluated
     * @return bool            TRUE on success, or FALSE on failure
     */
    public function free($result)
    {
        $this->_access['free']++;
        $success = $this->_dbMySql->free($result);
        if ($success === FALSE) {
            die ('Unable to free the result identifier');
        }
        return $success;
    }
    public function showAccess()
    {
        $this->_access['total'] = array_sum($this->_access);
        echo <<< EOT
        <div style="position: absolute; top: 0; right: 0; text-align: left; border: 1px solid black; margin: .5em; padding: 0.5em;">
        <h3>Database Access</h3>
        <pre>
EOT;
        print_r($this->_access);
        echo <<< EOT
        </pre>
        </div>
EOT;
    }
}
?>
